package cn.xinfei.xdecision.engine.job;

import cn.xinfei.xdecision.common.utils.util.JsonUtil;
import cn.xinfei.xdecision.constant.EngineResultEnum;
import cn.xinfei.xdecision.engine.runner.api.DecisionRerunApi;
import cn.xinfei.xdecision.model.DecisionReentryApiRequest;
import cn.xinfei.xdecision.model.DecisionReentryResponse;
import com.alibaba.fastjson.JSONObject;
import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import com.xxl.job.core.context.XxlJobHelper;

/**
 * 尚未经过测试验证...........
 */
@Slf4j
@Service
public class XDecisionRerunJob {

    @Autowired
    private MeterRegistry meterRegistry;

    @Autowired
    private DecisionRerunApi decisionRerunApi;

    private static final DecisionReentryApiRequest API_REQUEST = new DecisionReentryApiRequest();

    @XxlJob(value = "riskRerunJob", init = "init", destroy = "destroy")
    public ReturnT<String> riskRerunJob(String param) {

        DecisionReentryApiRequest apiRequest = null;
        if (StringUtils.isNotEmpty(param)) {
            apiRequest = JSONObject.parseObject(param, DecisionReentryApiRequest.class);
        } else {
            apiRequest = API_REQUEST;
        }

        // 分片序号
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        int shardIndex = shardingVo.getIndex();
        // 分片总数
        int shardTotal = shardingVo.getTotal();
        XxlJobLogger.log("分片参数，当前分片序号={},总分片数={}", shardIndex, shardTotal);
        apiRequest.setShardIndex(shardIndex);
        apiRequest.setShardTotal(shardTotal);

        return riskRerunJob(apiRequest);
    }

    private ReturnT<String> riskRerunJob(DecisionReentryApiRequest apiRequest) {
        log.info("riskRerunJob apiRequest:{}", apiRequest);
        long start = System.currentTimeMillis();
        Transaction transaction = Cat.newTransaction("xengine", "reentry");
        DecisionReentryResponse decisionApiResponse = new DecisionReentryResponse();
        try {
            decisionApiResponse = decisionRerunApi.rerun(apiRequest);
            log.info("riskRerunJob decisionApiResponse={}", decisionApiResponse);
            long end = System.currentTimeMillis();
            transaction.setDurationInMillis(end - start);
            transaction.setStatus(Transaction.SUCCESS);
        } catch (Exception e) {
            log.error("重入接口异常，error={},apiRequest={}", e.getMessage(), JsonUtil.toJson(apiRequest), e);
            decisionApiResponse.setMsg("重入接口异常," + e.getMessage());
            transaction.setStatus(e);
        } finally {
            transaction.complete();
            XxlJobLogger.log("重入任务处理完成，本次处理：" + JsonUtil.toJson(decisionApiResponse));
            MDC.clear();
        }
        String state = decisionApiResponse.getCode();
        if (EngineResultEnum.SUCCESS_END.getCode().equals(state)) {
            return ReturnT.SUCCESS;
        }
        return ReturnT.SUCCESS;
    }


    public void init() {
        log.info("init");
    }

    public void destroy() {
        log.info("destory");
    }

}
